<?php

/**
 * Author: Tran Quoc Anh
 * 
 * @category   default 
 * @copyright  Copyright (c) 2009 visualidea.org
 * @license    http://license.visualidea.org
 * @version    v 1.0 2009-04-15
 * 
 */
require_once 'modules/Book/models/Book.php';
require_once 'modules/language/models/Lang.php';
require_once 'modules/question/models/Question.php';
require_once 'modules/book/models/Chapter.php';
require_once 'modules/question/models/ProductCategory.php';
require_once 'modules/content/models/ContentCategory.php';
require_once 'modules/question/models/Answer.php';
require_once 'modules/content/models/Content.php';
require_once 'modules/exercise/Models/Folder.php';
require_once 'modules/exercise/Models/ExerciseParameter.php';
require_once 'modules/exercise/Models/ExerciseLib.php';

define('MODULE_PATH', './modules/epub');
define('TEMPLATE', MODULE_PATH . '/template');
define('OUTPUT', MODULE_PATH . '/output');
define('OEBPS_PATH', OUTPUT . '/OEBPS');
$guid = str_replace(array('{', '-', '}'), '', com_create_guid());
define('GUID', $guid);

class Epub_AdminController extends Nine_Controller_Action_Admin {

    public function exportEpubAction() {
        $group = Nine_Registry::getLoggedInGroupId();
        $userid = Nine_Registry::getLoggedInUserId();
        $this->view->group = $group;


        $objBook = new Models_Book();
        $objLang = new Models_Lang();
        $objChapter = new Models_Chapter();
        $objCatQuestion = new Models_ContentCategory();
        $objQuestion = new Models_Question();
        $objAnswer = new Models_Answer();
        $objContent = new Models_Content();
        $objFolder = new Models_Folder();
        $objExerciseParameter = new Models_ExerciseParameter();
        $objExerciseLib = new Models_ExerciseLib();
        /**
         * Check permission
         */
        if (false == $this->checkPermission('export', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }

        $this->view->headTitle('Export Epub ');

        $content = '';
        $spin = '';
        $config = Nine_Registry::getConfig();
        $gid = $this->_getParam('id', false);


        /**
         * Get Book
         * */
        $data = $objBook->getBookById($gid);
        $lang_id = $data['lang_id'];
//        $lang_id = 1;
        //echo '<p>'.$data['title'].'</p>';
        $this->e_init();
        $this->e_editTitlePage($data['title']);
        $this->e_editTocNCX($data['title']);
        
        
        
        
        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);

        $this->view->date = $date;



        /**
         * Get Chapter
         * */
        // load chapter of book
        $chaps = $data['chapter_ids'];
//        echo '<p>chapter:'.$data['chapter_ids'].'</p>';
        $chapters = explode("_", $chaps);
        $bookChapters = array();
        $i = 1;
        if (count($chapters) > 1) {
            foreach ($chapters as $id) {
                if ($id != 0) {
//                    echo '<p>lang:'.$lang_id.'</p>';
//                    echo '<p>chapter:'.$id.'</p>';
                    $chap = $objChapter->setAllLanguages(true)->getChapterBy_Id($id, $lang_id);
//                    echo '<p>chapter:'.$chap['name'].'</p>';
                    //$book_ques = $objQuestion->setAllLanguages(true)->getQuestionBy_gId(2);

                    if ($chap) {

                        //Add Multichoices Question
                        copy(OEBPS_PATH . '/Text/chapter.xhtml', OEBPS_PATH . '/Text/chapter-' . $i . '.xhtml');

                        $file = OEBPS_PATH . '/Text/chapter-' . $i . '.xhtml';
                        $handle = fopen($file, 'r');
                        $data1 = fread($handle, filesize($file));
                        Utils::replaceWithTag('CHAPTER_TITLE', $data1, $chap['name']);
//                        echo '<p>name:'.$chap['name'].'</p>';
                        $ques = explode("_", $chap['question_ids']);
//                        echo '<p>questions:'.$chap['question_ids'].'</p>';
                        $quest_HTML = '';
                        $book_questions = array();
                        if (count($ques) > 1) {
                            
                            $j = 1;
                            foreach ($ques as $q) {
                                if ($q != 0) {
                                    $book_ques = $objQuestion->setAllLanguages(true)->getQuestionBy_Id($q, $lang_id);
                                    if ($book_ques) {
                                        $allAnswers = $objAnswer->setAllLanguages(true)->getAnserById($book_ques['question_gid'], $lang_id);
                                        $q_as = array('question' => $book_ques, 'answers' => $allAnswers);
                                        array_push($book_questions, $q_as);

                                        $quest_HTML .= '<div class="row question" object="ques_' . $j . '">
														  <div class=" alert alert-info"><span>' . $j . '. </span>' . $book_ques['full_text'] . '</div>
														  		<ol class="answer" style="list-style-type: upper-alpha;">';
                                        foreach ($allAnswers as $ans) {
                                            if ($ans['is_true'] == 1) {
                                                $quest_HTML .= '<li class=" ques_' . $j . '"  onclick="choiceAns($(this),\'ques_' . $j . '\',false,true)"><input type="hidden" value="1" />' . $ans['content'] . '</li>';
                                            } else {
                                                $quest_HTML .= '<li class=" ques_' . $j . '"  onclick="choiceAns($(this),\'ques_' . $j . '\',false,true)">' . $ans['content'] . '</li>';
                                            }
                                        }
                                        $quest_HTML .= '</ol>
														  </div>
														<br/>';
                                        $j += 1;
                                    }
                                }
                            }
                        }
                        $c_qs = array('chapter' => $chap, 'questions' => $book_questions);
                        array_push($bookChapters, $c_qs);

                        Utils::replaceWithTag('QUESTIONS', $data1, $quest_HTML);

                        $handle = fopen($file, 'w') or die('Cannot open file:  ' . $file);

                        fwrite($handle, $data1);

                        fclose($handle);

                        if ($chap["lecture_ids"]) {
                            //Add Lecture
                            $lecs = explode("_", $chap['lecture_ids']);
                            foreach ($lecs as $l) {
                                if ($l == 0)
                                    continue;
                                $lect = $objContent->setAllLanguages(true)->getContentByGId($l, $lang_id);

                                if ($lect) {
                                    copy(OEBPS_PATH . '/Text/lecture.xhtml', OEBPS_PATH . '/Text/lecture-' . $lect["content_id"] . '.xhtml');

                                    $file = OEBPS_PATH . '/Text/lecture-' . $lect["content_id"] . '.xhtml';
                                    $handle = fopen($file, 'r');
                                    $data2 = fread($handle, filesize($file));
                                    $content_lecture = $lect["full_text"];
                                    if (strpos($content_lecture, '<img') !== false) {
                                        $doc = new DOMDocument();
                                        @$doc->loadHTML($content_lecture);

                                        $tags = $doc->getElementsByTagName('img');

                                        foreach ($tags as $tag) {
                                            $src = $tag->getAttribute('src');
                                            $img_url = substr($src, strpos(substr($src, 1),'/') + 1);
                                            copy('./' . $img_url, OEBPS_PATH . '/Images/' . basename($img_url));
                                            $lect["full_text"] = str_replace($src, '../Images/' . basename($img_url), $lect["full_text"]);

                                            $content = $content . '<item href="Images/' . basename($img_url) . '" id="' . basename($img_url) . '" media-type="image/jpg" />';
                                        }
                                    }
                                    Utils::replaceWithTag('CHAPTER_TITLE', $data2, $chap['name']);
                                    Utils::replaceWithTag('TITLE', $data2, $lect["title"]);
                                    Utils::replaceWithTag('CONTENT', $data2, $lect["full_text"]);
                                    $handle = fopen($file, 'w') or die('Cannot open file:  ' . $file);

                                    fwrite($handle, $data2);

                                    fclose($handle);

                                    $content = $content . '<item href="Text/lecture-' . $lect["content_id"] . '.xhtml" id="lecture-' . $lect["content_id"] . '.xhtml" media-type="application/xhtml+xml" />';
                                    $spin .= '<itemref idref="lecture-' . $lect["content_id"] . '.xhtml"/>';
                                }
                            }
                                                      
                            
                        }
                        
                        //Add demo
                        if ($chap['folder_ids']) {
                            $demo_ids = explode("_", $chap['folder_ids']);
                            foreach ($demo_ids as $demo_id) {
                                if ($demo_id == 0)
                                    continue;
                                $this->add_demo($demo_id, $content, $spin);
                            }
                        }
                        
                        //add exercise
                        if($chap['exercise_ids']){
                            //Add demo
                            $exercise_ids = explode("_", $chap['exercise_ids']);
                            foreach ($exercise_ids as $exercise_id) {
                                if ($exercise_id == 0)
                                    continue;
                                $this->add_exsercise($exercise_id, $lang_id, $content, $spin);
                            }
                        }
                        
                        $content = $content . '<item href="Text/chapter-' . $i . '.xhtml" id="chapter-' . $i . '.xhtml" media-type="application/xhtml+xml" />';
                        $spin .= '<itemref idref="chapter-' . $i . '.xhtml"/>';
                                                
                        $i++;
                    }
                }
            }
        }
//        die;
//        $tags = $merge_doc->getElementsByTagName('itemref');
//
//        foreach ($tags as $tag) {
//            $spin .= $merge_doc->saveHTML($tag);
//        }
        $this->e_editContentOPF($content, $spin, $data["title"]);

        /**
         * Set values for tempalte
         */
        $this->Zip(OUTPUT, MODULE_PATH . '/file_' . $userid . '.epub');

//         header('Content-type: application/epub+zip');
// 		// It will be called test.zip
// 		header('Content-Disposition: attachment; filename="file_'.$userid.'.epub"');
// 		//read a file and send
// 		readfile(MODULE_PATH.'/file_'.$userid.'.epub');
        $path = MODULE_PATH . '/file_' . $userid . '.epub';
        print_r($path); die;
        
        if (!file_exists($path)) {
            // File doesn't exist, output error
            die('file not found');
        } else {
            $size = filesize($path);
            $file = basename($path);
//            print_r(readfile($path)); die;
            // Set headers
            header("Pragma: public"); // required
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: private", false); // required for certain browsers
            header("Content-Description: File Transfer");
            header("Content-Disposition: attachment; filename=\"$file\"");
            header("Content-Type: application/epub+zip");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: $size");
            // Read the file from disk
            readfile($path);
        }
        
        unlink(MODULE_PATH . '/file_' . $userid . '.epub');
        Utils::deleteDirectory(OUTPUT);
        Utils::deleteDirectory(MODULE_PATH . '/merge');
        exit();
    }

    function e_init() {
        Utils::deleteDirectory(OUTPUT);
        if (!Utils::copyDirectory(TEMPLATE, OUTPUT)) {
            echo 'Cannot create folder container!';
            return FALSE;
        }
    }

    function e_editContentOPF($content, $spin, $name) {

        $file = OEBPS_PATH . '/content.opf';
        $handle = fopen($file, 'r');
        $data = fread($handle, filesize($file));
        Utils::replaceWithTag('TITLE', $data, $name);
        Utils::replaceWithTag('CATEGORY', $data, 'BK');
        Utils::replaceWithTag('LANG', $data, 'en');
        Utils::replaceWithTag('RIGHT', $data, 'Public Domain');
        Utils::replaceWithTag('PUBLISHER', $data, 'BKED.com');
        Utils::replaceWithTag('UID', $data, 'BKED.com' . GUID);
        Utils::replaceWithTag('CONTENT', $data, $content);
        Utils::replaceWithTag('SPIN', $data, $spin);
        $handle = fopen($file, 'w') or die('Cannot open file:  ' . $file);

        fwrite($handle, $data);

        fclose($handle);
    }

    function e_editTocNCX($name) {

        $file = OEBPS_PATH . '/toc.ncx';
        $handle = fopen($file, 'r');
        $data = fread($handle, filesize($file));

        Utils::replaceWithTag('TITLE', $data, $name);
        Utils::replaceWithTag('UID', $data, 'BKED.com' . GUID);

        $handle = fopen($file, 'w') or die('Cannot open file:  ' . $file);

        fwrite($handle, $data);

        fclose($handle);
    }

    function e_editTitlePage($name) {

        $file = OEBPS_PATH . '/Text/title_page.xhtml';
        $handle = fopen($file, 'r');
        $data = fread($handle, filesize($file));

        Utils::replaceWithTag('TITLE', $data, $name);

        $handle = fopen($file, 'w') or die('Cannot open file:  ' . $file);

        fwrite($handle, $data);
        fflush($handle);
        fclose($handle);
    }
    
    function add_demo($demo_id, &$content, &$spin){
        //add demo
        $objFolder = new Models_Folder();
        $folder = $objFolder->getFolderById($demo_id);
        if ($folder) {
            $dir = OEBPS_PATH . '/Demo/'.$demo_id;
            $this->UnZip($folder['files'], $dir);
//            Utils::copyDirectory(MODULE_PATH . '/merge/OEBPS', OEBPS_PATH . '/Text/OEBPS');
            
            //add html file
            $file_html = scandir($dir);
            foreach ($file_html as $key => $value) {
                if($value == '.' || $value == '..')
                        continue;
                if(!is_dir($dir.'/'.$value)){
                    $content = $content . '<item href="Demo/'. $demo_id.'/' . $value . '" id="demo-' . $demo_id.'-'.$value . '" media-type="application/xhtml+xml" />';
                    $spin = $spin.'<itemref idref="demo-' . $demo_id.'-'.$value . '"/>';
                }
            }
            
            //add css file
            if(file_exists($dir.'/css')){
                $file_css = scandir($dir.'/css');
                foreach ($file_css as $key => $value) {
                    if($value == '.' || $value == '..')
                            continue;
                    if(!is_dir($dir.'/'.$value)){
                        $content = $content . '<item href="Demo/'. $demo_id.'/css/'  . $value . '" id="demo-' . $demo_id.'-'.$value . '" media-type="text/css" />';
                    }
                }
            }
            
            //add js file
            if(file_exists($dir.'/js')){
                $file_js = scandir($dir.'/js');
                foreach ($file_js as $key => $value) {
                    if($value == '.' || $value == '..')
                            continue;
                    if(!is_dir($dir.'/'.$value)){
                        $content = $content . '<item href="Demo/'. $demo_id.'/js/'  . $value . '" id="demo-' . $demo_id.'-'.$value . '" media-type="text/plain" />';
                    }
                }
            }
        }
    }
    
    function add_exsercise($exercise_id, $lang_id, &$content, &$spin){
        //add demo
        $objExercisePara = new Models_ExerciseParameter();
        $objExerciseLib = new Models_ExerciseLib();
        $exercisePara = $objExercisePara->setAllLanguages(true)->getExercise_ParameterBy_Id($exercise_id, $lang_id);
        
        if ($exercisePara) {
            $folder = $objExerciseLib->getExercise_LibById($exercisePara['exercise_lib_id']);
            $dir = OEBPS_PATH . '/Exercise/'.$exercise_id;
            Utils::copyDirectory($folder['path'], $dir);
//            echo $folder['path']; die;
//            Utils::copyDirectory(MODULE_PATH . '/merge/OEBPS', OEBPS_PATH . '/Text/OEBPS');
            
            $file = $dir . '/index.html';
            $handle = fopen($file, 'r');
            $data = fread($handle, filesize($file));
            Utils::replaceWithTag('INPUT', $data, $exercisePara['parameter']);
            $handle = fopen($file, 'w') or die('Cannot open file:  ' . $file);

            fwrite($handle, $data);

            fclose($handle);
            
            //add html file
            $content = $content . '<item href="Exercise/'. $exercise_id.'/index.html" id="Exercise-' . $exercise_id.'-index.html" media-type="application/xhtml+xml" />';
            $spin = $spin.'<itemref idref="Exercise-' . $exercise_id.'-index.html"/>';
            
            //add css file
            if(file_exists($dir.'/css')){
                $file_css = scandir($dir.'/css');
                foreach ($file_css as $key => $value) {
                    if($value == '.' || $value == '..')
                            continue;
                    if(!is_dir($dir.'/'.$value)){
                        $content = $content . '<item href="Exercise/'. $exercise_id.'/css/'  . $value . '" id="Exercise-' . $exercise_id.'-'.$value . '" media-type="text/css" />';
                    }
                }
            }
            
            //add js file
            if(file_exists($dir.'/js')){
                $file_js = scandir($dir.'/js');
                foreach ($file_js as $key => $value) {
                    if($value == '.' || $value == '..')
                            continue;
                    if(!is_dir($dir.'/'.$value)){
                        $content = $content . '<item href="Exercise/'. $exercise_id.'/js/'  . $value . '" id="Exercise-' . $exercise_id.'-'.$value . '" media-type="text/plain" />';
                    }
                }
            }
        }
    }
    
    function UnZip($source, $destination) {
        $zip = new ZipArchive;
        $res = $zip->open($source);
        if ($res === TRUE) {
            $zip->extractTo($destination);
            $zip->close();
            return true;
        } else {
            return false;
        }
    }

    function Zip($source, $destination) {
// 	    if (!extension_loaded('zip') || !file_exists($source)) {
// 	        return false;
// 	    }

        $zip = new ZipArchive();
        if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
            return false;
        }

        $source = str_replace('\\', '/', realpath($source));

        if (is_dir($source) === true) {
            $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

            foreach ($files as $file) {
                $file = str_replace('\\', '/', $file);

                // Ignore "." and ".." folders
                if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..')))
                    continue;

                //$file = realpath($file);

                if (is_dir($file) === true) {
                    $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
                } else if (is_file($file) === true) {
                    $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                }
            }
        } else if (is_file($source) === true) {
            $zip->addFromString(basename($source), file_get_contents($source));
        }

        return $zip->close();
    }

}

class Utils {

    public static function deleteDirectory($dir) {
        if (!file_exists($dir))
            return true;
        if (!is_dir($dir))
            return unlink($dir);
        foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..')
                continue;
            if (!self::deleteDirectory($dir . DIRECTORY_SEPARATOR . $item))
                return false;
        }
        return rmdir($dir);
    }

    public static function copyDirectory($sourceDir, $targetDir) {
        if (!file_exists($sourceDir))
            return false;
        if (!is_dir($sourceDir))
            return copy($sourceDir, $targetDir);
        if (!file_exists($targetDir))
            if (!mkdir($targetDir))
                return false;
        foreach (scandir($sourceDir) as $item) {
            if ($item == '.' || $item == '..')
                continue;
            if (!self::copyDirectory($sourceDir . DIRECTORY_SEPARATOR . $item, $targetDir . DIRECTORY_SEPARATOR . $item)) {
                //chmod($targetDir,0777);
                return false;
            }
        }
        return true;
    }

    public static function replaceWithTag($tag, &$str, $value) {
        $str = str_replace('[' . $tag . ']', $value, $str);
    }

}